<?php

namespace App\Http\Controllers;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, ValidatesRequests;

    // 成功返回
    public function success($message, $data = [], $total = null): array
    {
        $response = [
            "code" => 200,
            "msg" => $message,
            "data" => $data,
        ];
        if ($total !== null) {
            $response['total'] = $total;
        }
        return $response;
    }

    // 失败返回
    public function error($message, $data = []): array
    {
        return [
            "code" => 201,
            "msg" => $message,
            "data" => $data
        ];
    }

    // 处理路由
    public function dataTree($data, $pid)
    {
        $branch = [];
        foreach ($data as $item) {
            if ($item->menus_id == $pid) {
                $children = $this->dataTree($data, $item->id);

                if ($children) {
                    $item->children = $children;
                }
                $branch[] = $item;
            }
        }
        return $branch;
    }

    public function request_get(string $url, $params = [])
    {
        // 创建一个新的 Guzzle HTTP 客户端实例
        $client = new Client();

        // 发起 POST 请求（此处仅为示例，也可以是 GET、PUT、DELETE 等其他 HTTP 方法）
        try {
            $response = $client->get($url, $params);

            // 获取响应体内容并将其转换为 JSON 格式
            $responseData = json_decode($response->getBody(), true);

            // 处理并返回响应数据
            return $responseData;
        } catch (GuzzleException $e) {
            // 抛出或处理请求过程中的任何异常
            report($e);
            return response()->json(['error' => 'Failed to fetch data from third party API'], 500);
        }
    }

    public function request_post(string $url, array $data)
    {
        // 创建一个新的 Guzzle HTTP 客户端实例
        $client = new Client();

        // 发起 POST 请求（此处仅为示例，也可以是 GET、PUT、DELETE 等其他 HTTP 方法）
        try {
            $response = $client->post($url, $data);

            // 获取响应体内容并将其转换为 JSON 格式
            $responseData = json_decode($response->getBody(), true);

            // 处理并返回响应数据
            return $responseData;
        } catch (GuzzleException $e) {
            // 抛出或处理请求过程中的任何异常
            report($e);
            return response()->json(['error' => 'Failed to fetch data from third party API'], 500);
        }
    }

    /**
     * 创建验证码
     */
    protected function generateVerificationCode(int $length = 6)
    {
        $verificationCode = '';
        for ($i = 0; $i < $length; $i++) {
            $verificationCode .= mt_rand(0, 9);
        }
        return $verificationCode;
    }
}
